<?php

namespace app\common\model;

use think\Cache;
use think\Model;

/**
 * 地区数据模型
 */
class Area extends Model
{

    /**
     * 根据经纬度获取当前地区信息
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area 城市信息
     */
    public static function getAreaFromLngLat($lng, $lat, $level = 3)
    {
        $namearr = [1 => 'geo:province', 2 => 'geo:city', 3 => 'geo:district'];
        $rangearr = [1 => 15000, 2 => 1000, 3 => 200];
        $geoname = isset($namearr[$level]) ? $namearr[$level] : $namearr[3];
        $georange = isset($rangearr[$level]) ? $rangearr[$level] : $rangearr[3];
        // 读取范围内的ID
        $redis = Cache::store('redis')->handler();
        $georadiuslist = [];
        if (method_exists($redis, 'georadius')) {
            $georadiuslist = $redis->georadius($geoname, $lng, $lat, $georange, 'km', ['WITHDIST', 'COUNT' => 5, 'ASC']);
        }

        if ($georadiuslist) {
            list($id, $distance) = $georadiuslist[0];
        }
        $id = isset($id) && $id ? $id : 3;
        return self::get($id);
    }

    /**
     * 根据经纬度获取省份
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area
     */
    public static function getProvinceFromLngLat($lng, $lat)
    {
        $provincedata = null;
        $citydata = self::getCityFromLngLat($lng, $lat);
        if ($citydata) {
            $provincedata = self::get($citydata['pid']);
        }
        return $provincedata;
    }

    /**
     * 根据经纬度获取城市
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area
     */
    public static function getCityFromLngLat($lng, $lat)
    {
        $citydata = null;
        $districtdata = self::getDistrictFromLngLat($lng, $lat);
        if ($districtdata) {
            $citydata = self::get($districtdata['pid']);
        }
        return $citydata;
    }

    /**
     * 根据经纬度获取地区
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     * @return Area
     */
    public static function getDistrictFromLngLat($lng, $lat)
    {
        $districtdata = self::getAreaFromLngLat($lng, $lat, 3);
        return $districtdata;
    }


    /**
     * 根据区县ID获取地址
     */
    public static function getAddressByCountyId($county_id){
        if(!$county_id) return "";
        $county = self::get($county_id);
        if(!$county) return "";
        if($county->level!=3) return "";
        return $county->mergename;
    }

    /*
     *  根据经纬度获取详细地址
     */
    public static function getCityInfo($longitude, $latitude){
        //$longitude = number_format(doubleval(input('longitude/s')), 6);
        //$latitude = number_format(doubleval(input('latitude/s')), 6);

        $url = 'http://api.map.baidu.com/geocoder/v2/';
        $gps = $latitude.','.$longitude;
        $param = array(
            'location' => $gps,
            'pois' => 0,
        );
        $baidu_key = 'UlKU3yScanaFshPPzDOmw31i';

        $param['ak'] = $baidu_key;
        $param['output'] = 'json'; 
        $url = $url.'?'.http_build_query($param, '', '&');
        
        $result = array();
        $result = json_decode(self::curl_get($url), true);
        return $result;
    }

    private static function curl_get($url, $milliseconds = 300)
    {
        $start_time = microtime(true);

        $ch = curl_init();
        //这个参数很重要，设置这个才可以支持毫秒级的超时设置
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        //curl_setopt($ch, CURLOPT_USERAGENT, self::$useragent);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_FAILONERROR, 0);
        //curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, self::$connecttimeout);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, $milliseconds);


        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $response = curl_exec($ch);
        $http_error_code = curl_errno($ch);
        curl_close($ch);

        //EdjLog::info("request to baidu lbs api, url is $url, cost time:" . (microtime(true) - $start_time));
        //EdjLog::info("baidu http_error:$http_error_code response is " . str_replace(PHP_EOL, '', $response));
        return $response;
    }

}
